package com.xbongbong.paas.service.impl;

import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.pojo.dto.CallCenterModuleDTO;
import com.xbongbong.paas.pojo.vo.CallCenterModuleVO;
import com.xbongbong.paas.pojo.vo.CallCenterOrgGetByCorpIdVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.service.CallCenterCommonService;
import com.xbongbong.paas.service.CallCenterOrganizationService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CallCenterErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.callcenter.CallCenterConstant;
import com.xbongbong.saas.domain.entity.CallCenterOrganizationEntity;
import com.xbongbong.saas.model.CallCenterOrganizationModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author youli.chen
 * @version v1.0
 * @description: 呼叫中心企业实现类
 * @date 2019/2/13 16:25
 * @since v1.0
 */
@Service("callCenterOrganizationService")
public class CallCenterOrganizationServiceImpl implements CallCenterOrganizationService {

    @Resource
    private CallCenterOrganizationModel callCenterOrganizationModel;
    @Resource
    private CallCenterCommonService callCenterCommonService;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    /**
     * 获取公司在该平台的apikey
     *
     * @param corpid     公司id
     * @param moduleType 微应用平台，参考CallCenterTypeEnum
     * @return String 不存在则返回null
     */
    @Override
    public String getApiKey(String corpid, Integer moduleType) throws XbbException {
        String apiKey = paasRedisHelper.getValue(CallCenterConstant.REDIS_KEY_API_KEY,
                corpid + StringConstant.COLON + moduleType);
        if (StringUtil.isEmpty(apiKey)) {
            Map<String, Object> params = new HashMap<>(6);
            params.put("corpid", corpid);
            params.put("moduleType", moduleType);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put("columns", "apikey");
            params.put("start", 0);
            params.put("pageNum", 1);
            List<CallCenterOrganizationEntity> list = callCenterOrganizationModel.findEntitys(params);
            apiKey = list.size() == 0 ? null : list.get(0).getApikey();
            if (StringUtil.isNotEmpty(apiKey)) {
                paasRedisHelper.setValue(CallCenterConstant.REDIS_KEY_API_KEY, corpid + StringConstant.COLON + moduleType,
                        apiKey, RedisConstant.COMMON_DURATION);
            }
        }
        return apiKey;
    }

    /**
     * 获取公司在该平台的公司信息
     *
     * @param corpid     公司id
     * @param moduleType 微应用平台，参考CallCenterTypeEnum
     * @return CallCenterOrgGetByCorpIdVO 获取公司在该平台的公司信息回参
     * @throws XbbException
     */
    @Override
    public CallCenterOrgGetByCorpIdVO getByCorpId(String corpid, Integer moduleType) throws XbbException {
       return callCenterOrganizationModel.getByCorpId(corpid, moduleType);
    }

    /**
     * 获取该公司是否有权限使用语音转写功能
     *
     * @param corpid     公司id
     * @param moduleType 话务中心平台
     * @param userId
     * @return 是否有权限使用语音转写功能
     * @throws XbbException
     * @version v1.0
     * @since v1.0
     */
    @Override
    public Boolean isAudioTranslate(String corpid, Integer moduleType, String userId) throws XbbException {
        CallCenterModuleDTO callCenterModuleDTO = new CallCenterModuleDTO();
        callCenterModuleDTO.setCorpid(corpid);
        callCenterModuleDTO.setUserId(userId);
        CallCenterModuleVO callCenterModuleVO = callCenterCommonService.module(callCenterModuleDTO);
        if (callCenterModuleVO == null) {
            return false;
        }

        String enable = paasRedisHelper.getValue(CallCenterConstant.REDIS_KEY_ORG_AUDIO_TRANSLATE,
                corpid + StringConstant.COLON + moduleType);
        if (StringUtil.isEmpty(enable)) {
            Map<String, Object> params = new HashMap<>(6);
            params.put("corpid", corpid);
            params.put("moduleType", moduleType);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put("start", 0);
            params.put("pageNum", 1);
            params.put("columns", "is_audio_translate");
            List<CallCenterOrganizationEntity> list = callCenterOrganizationModel.findEntitys(params);
            if (list.size() == 0) {
                enable = "false";
            } else {
                enable = String.valueOf(list.get(0).getIsAudioTranslate());
            }
            paasRedisHelper.setValue(CallCenterConstant.REDIS_KEY_ORG_AUDIO_TRANSLATE,
                    corpid + StringConstant.COLON + moduleType, enable, RedisConstant.COMMON_DURATION);
        }
        return Boolean.parseBoolean(enable);
    }

    /**
     * 设置公司使用语音转写功能的能力
     *
     * @param org              公司
     * @param isAudioTranslate 是否启用
     * @throws XbbException
     * @version v1.0
     * @since v1.0
     */
    @Override
    public void enableAudioTranslate(CallCenterOrganizationEntity org, Boolean isAudioTranslate) throws XbbException {
        org.setIsAudioTranslate(isAudioTranslate);
        callCenterOrganizationModel.update(org);
        paasRedisHelper.setValue(CallCenterConstant.REDIS_KEY_ORG_AUDIO_TRANSLATE, org.getCorpid() + StringConstant.COLON +
                        org.getModuleType(), isAudioTranslate.toString(), RedisConstant.COMMON_DURATION);
    }

    /**
     * 当前公司逍邦邦呼叫中心对应的换卡套餐是否开通并且有效(按照当前时间实时计算)
     * @param corpid
     * @param moduleType
     * @return
     * @throws XbbException
     */
    @Override
    public Integer callBlockServer(String corpid, Integer moduleType) throws XbbException{
        // 0:未开通，或者无效
        Integer callBlockServer = BasicConstant.ZERO;
        // 换卡充值
        CallCenterOrgGetByCorpIdVO getByCorpIdVO = getByCorpId(corpid, moduleType);
        if (getByCorpIdVO == null) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301001);
        }
        Boolean callBlockRuleOrg = getByCorpIdVO.getCallBlockRule();
        Integer callBlockStarTime = getByCorpIdVO.getCallBlockStarTime();
        Integer callBlockEndTime = getByCorpIdVO.getCallBlockEndTime();
        if(callBlockRuleOrg!=null && callBlockRuleOrg && callBlockStarTime != null && callBlockEndTime != null){
            // 向上取整
            Integer betweenDays = (int)Math.ceil(DateUtil.betweenDays(DateUtil.getInt(), callBlockEndTime));
            // 差值补偿
            betweenDays = Objects.equals(0, betweenDays) ? Integer.valueOf(1) : betweenDays;
            if(betweenDays > 3){
                // 1:开通服务并且在有效期内
                callBlockServer = BasicConstant.ONE;
            } else if(betweenDays < 0){
                // 2:开通服务并且失效
                callBlockServer = BasicConstant.TWO;
                // 失效之后关闭换卡服务套餐
                CallCenterOrganizationEntity org = new CallCenterOrganizationEntity();
                BeanUtil.copyProperties(getByCorpIdVO, org);
                org.setCallBlockRule(false);
                callCenterOrganizationModel.update(org);
            } else if(betweenDays > 0 && betweenDays < 4){
                // 1:开通服务并且临近有效期
                callBlockServer = BasicConstant.ONE;
            }
        }
        return callBlockServer;
    }
}
